<template>
  <PageContainer title="诊疗记录管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchForm.keyword" placeholder="请输入宠物名称/诊断结果搜索" prefix-icon="el-icon-search"
            class="search-input" @change="handleSearch"></el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.appointmentId" placeholder="请选择预约ID筛选" class="status-select"
            @change="handleSearch">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="item in appointmentOptions" :key="item.appointmentId"
              :label="`预约ID: ${item.appointmentId}`" :value="item.appointmentId"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="date-picker"
            @change="handleSearch"></el-date-picker>
        </el-col>
        <el-col :span="4" class="operate-buttons">
          <el-button type="primary" @click="handleAddTreatment">
            <i class="el-icon-plus"></i> 新增诊疗记录
          </el-button>
          <el-button type="primary" @click="handleRefresh" style="margin-left: 10px;">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 诊疗统计卡片 -->
    <div class="consult-stats" style="margin-top: 20px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-s-order stat-icon"></i>
              <h4>今日诊疗数</h4>
            </div>
            <div class="stat-value">{{ todayTreatmentCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-s-flag stat-icon"></i>
              <h4>本月诊疗数</h4>
            </div>
            <div class="stat-value">{{ monthTreatmentCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-s-shop stat-icon"></i>
              <h4>累计诊疗数</h4>
            </div>
            <div class="stat-value">{{ totalTreatmentCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-money stat-icon"></i>
              <h4>累计收入</h4>
            </div>
            <div class="stat-value">¥{{ totalIncome.toFixed(2) }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 诊疗记录列表表格 -->
    <el-table :data="treatmentList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;">
      <el-table-column label="诊疗ID" prop="treatmentId" width="100" align="center"></el-table-column>
      <el-table-column label="预约ID" width="100" align="center">
        <template #default="scope">{{ scope.row.appointmentId || '无' }}</template>
      </el-table-column>
      <el-table-column label="宠物名称" width="120" align="center">
        <template #default="scope">{{ scope.row.appointment.pet?.name || '未知' }}</template>
      </el-table-column>
      <el-table-column label="宠物类型" width="120" align="center">
        <template #default="scope">{{ scope.row.appointment.pet?.type || '未知' }}</template>
      </el-table-column>
      <el-table-column label="诊断结果" prop="diagnosis" width="200" align="center"></el-table-column>
      <el-table-column label="治疗方案" prop="treatmentPlan" width="250" align="center"></el-table-column>
      <el-table-column label="使用药品" width="200" align="center">
        <template #default="scope">
          <div class="drug-tags">
            <el-tag v-for="drug in scope.row.drugs" :key="drug.drugId" type="info" size="small" effect="light">
              {{ drug.name }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="诊疗费用" prop="cost" width="100" align="center">
        <template #default="scope">¥{{ scope.row.cost.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column label="诊疗时间" prop="createDate" width="180" align="center">
        <template #default="scope">{{ formatDate(scope.row.createDate) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleViewDetail(scope.row)">详情</el-button>
          <el-button type="text" @click="handleEditTreatment(scope.row)" style="color: #409eff;">编辑</el-button>
          <el-button type="text" @click="handleDeleteTreatment(scope.row)" style="color: #f56c6c;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="filteredTotal" :page-size="pageSize" :current-page="currentPage"
      @size-change="handleSizeChange" @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right;">
    </TablePagination>

    <!-- 诊疗详情弹窗 -->
    <el-dialog title="诊疗详情" :visible.sync="detailVisible" width="900px" :before-close="handleDetailClose">
      <div class="treatment-detail">
        <div class="detail-header">
          <div class="header-left">
            <h3>诊疗ID：{{ currentTreatment.treatmentId }}</h3>
            <el-tag type="success">已完成</el-tag>
          </div>
          <div class="header-right">
            <p>诊疗时间：{{ formatDate(currentTreatment.createDate) }}</p>
            <p>预约ID：{{ currentTreatment.appointment.appointmentId }}</p>
            <p>医生：{{ currentTreatment.appointment.doctorName || '未知' }}</p>
          </div>
        </div>

        <div class="detail-section">
          <h4>宠物主人信息</h4>
          <el-table :data="[currentTreatment.appointment.ownerUser]" border style="width: 100%;">
            <el-table-column label="主人姓名" prop="nickName" width="150" align="center"></el-table-column>
            <el-table-column label="联系电话" prop="phone" width="150" align="center">
              <template #default="scope">{{ scope.row.phone || '未填写' }}</template>
            </el-table-column>
            <el-table-column label="所在地区" width="150" align="center">
              <template #default="scope">
                {{ `${scope.row.province || ''}${scope.row.city || ''}` }}
              </template>
            </el-table-column>
            <el-table-column label="备注" width="300">
              <template #default="scope">{{ scope.row.petOwner?.notes || '无' }}</template>
            </el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>宠物信息</h4>
          <el-table :data="[currentTreatment.appointment.pet]" border style="width: 100%;">
            <el-table-column label="宠物名称" prop="name" width="120" align="center"></el-table-column>
            <el-table-column label="宠物类型" prop="type" width="120" align="center"></el-table-column>
            <el-table-column label="宠物年龄" width="120" align="center">
              <template #default="scope">{{ calculatePetAge(scope.row.birthday) || '未知' }}</template>
            </el-table-column>
            <el-table-column label="宠物品种" prop="breed" width="150" align="center"></el-table-column>
            <el-table-column label="就诊症状" prop="symptom"></el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>诊疗信息</h4>
          <el-table :data="[{
            diagnosis: currentTreatment.diagnosis,
            treatmentPlan: currentTreatment.treatmentPlan,
            cost: currentTreatment.cost,
            createDate: currentTreatment.createDate
          }]" border style="width: 100%;">
            <el-table-column label="诊断结果" prop="diagnosis" width="200" align="center"></el-table-column>
            <el-table-column label="治疗方案" prop="treatmentPlan" width="300" align="center"></el-table-column>
            <el-table-column label="诊疗费用" prop="cost" width="120" align="center">
              <template #default="scope">¥{{ scope.row.cost.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column label="诊疗时间" prop="createDate" width="180" align="center">
              <template #default="scope">{{ formatDate(scope.row.createDate) }}</template>
            </el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>使用药品明细</h4>
          <el-table :data="currentTreatment.drugs" border style="width: 100%;"
            v-if="currentTreatment.drugs && currentTreatment.drugs.length > 0">
            <el-table-column label="药品ID" prop="drugId" width="100" align="center"></el-table-column>
            <el-table-column label="药品名称" prop="name" width="150" align="center"></el-table-column>
            <el-table-column label="规格" prop="specification" width="150" align="center"></el-table-column>
            <el-table-column label="用法用量" prop="usages" width="200" align="center"></el-table-column>
            <el-table-column label="禁忌" prop="contraindication" width="200" align="center"></el-table-column>
            <el-table-column label="单价" prop="price" width="100" align="center">
              <template #default="scope">¥{{ scope.row.price.toFixed(2) }}</template>
            </el-table-column>
          </el-table>
          <div class="no-data" v-else>暂无药品使用记录</div>
        </div>
      </div>
    </el-dialog>

    <!-- 新增/编辑诊疗记录弹窗 -->
    <el-dialog :title="isEdit ? '编辑诊疗记录' : '新增诊疗记录'" :visible.sync="formVisible" width="800px">
      <el-form :model="treatmentForm" :rules="treatmentRules" ref="treatmentFormRef" label-width="120px">
        <el-form-item label="预约ID" prop="appointmentId">
          <el-select v-model="treatmentForm.appointmentId" placeholder="请选择预约" style="width: 100%;">
            <el-option v-for="item in appointmentOptions" :key="item.appointmentId"
              :label="`预约ID: ${item.appointmentId} (${item.pet?.name || '未知宠物'})`"
              :value="item.appointmentId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="诊断结果" prop="diagnosis">
          <el-input v-model="treatmentForm.diagnosis" type="textarea" :rows="3" placeholder="请输入诊断结果..."></el-input>
        </el-form-item>
        <el-form-item label="治疗方案" prop="treatmentPlan">
          <el-input v-model="treatmentForm.treatmentPlan" type="textarea" :rows="3" placeholder="请输入治疗方案..."></el-input>
        </el-form-item>
        <el-form-item label="使用药品" prop="drugIds">
          <el-select v-model="treatmentForm.drugIds" multiple placeholder="请选择使用的药品" style="width: 100%;">
            <el-option v-for="drug in drugOptions" :key="drug.drugId" :label="`${drug.name} (${drug.specification})`"
              :value="drug.drugId"></el-option>
          </el-select>
          <div class="form-hint">按住Ctrl键可多选药品</div>
        </el-form-item>
        <el-form-item label="诊疗费用" prop="cost">
          <el-input v-model="treatmentForm.cost" type="number" placeholder="请输入诊疗费用" prefix="¥"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确认提交</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import doctorApi from '@/api/doctor'
import { useAuthStore } from '@/store/modules/auth'

// 日期格式化工具（兼容Date对象和字符串）
const formatDate = (date) => {
  if (!date) return ''
  const targetDate = typeof date === 'string' ? new Date(date) : date
  if (isNaN(targetDate.getTime())) return ''
  const year = targetDate.getFullYear()
  const month = String(targetDate.getMonth() + 1).padStart(2, '0')
  const day = String(targetDate.getDate()).padStart(2, '0')
  const hour = String(targetDate.getHours()).padStart(2, '0')
  const minute = String(targetDate.getMinutes()).padStart(2, '0')
  const second = String(targetDate.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 计算宠物年龄
const calculatePetAge = (birthday) => {
  if (!birthday) return ''
  const birthDate = typeof birthday === 'string' ? new Date(birthday) : birthday
  if (isNaN(birthDate.getTime())) return ''
  const now = new Date()
  const ageDiff = now - birthDate
  const ageYear = Math.floor(ageDiff / (1000 * 3600 * 24 * 365))
  const ageMonth = Math.floor((ageDiff % (1000 * 3600 * 24 * 365)) / (1000 * 3600 * 24 * 30))
  return ageYear > 0 ? `${ageYear}岁${ageMonth}月` : `${ageMonth}月`
}

const authStore = useAuthStore()

// 页面局部存储doctorId
const doctorId = ref('')

// 搜索表单
const searchForm = reactive({
  keyword: '',
  appointmentId: '',
  dateRange: [] // [startDate, endDate]
})

// 原始全量数据（后端返回的医生专属全量数据）
const allTreatmentData = ref([])
// 分页后显示的数据
const treatmentList = ref([])
// 筛选后的总条数
const filteredTotal = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)

// 统计数据
const todayTreatmentCount = ref(0)
const monthTreatmentCount = ref(0)
const totalTreatmentCount = ref(0)
const totalIncome = ref(0)

// 下拉选项
const appointmentOptions = ref([])
const drugOptions = ref([])

// 弹窗相关
const detailVisible = ref(false)
const formVisible = ref(false)
const isEdit = ref(false)
const currentTreatment = ref({
  appointment: {
    pet: {},
    petOwner: {},
    ownerUser: {}
  },
  drugs: []
})

// 表单数据
const treatmentForm = reactive({
  treatmentId: '',
  appointmentId: '',
  diagnosis: '',
  treatmentPlan: '',
  drugIds: [],
  cost: 0
})

// 表单校验规则
const treatmentRules = reactive({
  appointmentId: [
    { required: true, message: '请选择预约', trigger: 'blur' }
  ],
  diagnosis: [
    { required: true, message: '请输入诊断结果', trigger: 'blur' },
    { min: 5, message: '诊断结果长度不能少于5字', trigger: 'blur' }
  ],
  treatmentPlan: [
    { required: true, message: '请输入治疗方案', trigger: 'blur' },
    { min: 10, message: '治疗方案长度不能少于10字', trigger: 'blur' }
  ],
  drugIds: [
    { required: true, message: '请选择至少一种药品', trigger: 'blur' },
    { type: 'array', min: 1, message: '请选择至少一种药品', trigger: 'blur' }
  ],
  cost: [
    { required: true, message: '请输入诊疗费用', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '费用不能小于0.01', trigger: 'blur' }
  ]
})

// 表单引用
const treatmentFormRef = ref(null)

// 核心：通过userinfoId获取医生ID（存储在页面局部变量doctorId）
const fetchDoctorId = async () => {
  try {
    // 1. 从Pinia读取userinfoId（不修改Pinia任何数据）
    const userinfoId = authStore.userinfoId

    // 2. 校验userinfoId是否存在
    if (!userinfoId) {
      ElMessage.error('未获取到用户信息，请重新登录')
      return false
    }

    // 3. 调用接口获取医生信息（包含doctorId）
    const res = await doctorApi.getCurrentDoctor(userinfoId)

    // 4. 提取doctorId并存储到页面局部变量
    if (res.data && res.data.doctorId) {
      doctorId.value = res.data.doctorId
      return true
    } else {
      ElMessage.error('获取医生信息失败：接口未返回doctorId')
      return false
    }
  } catch (error) {
    ElMessage.error('获取医生信息失败')
    return false
  }
}

// 获取预约列表（用于下拉选项）
const fetchAppointmentOptions = async () => {
  try {
    // 先确保获取到doctorId
    if (!doctorId.value && !(await fetchDoctorId())) {
      return
    }

    // 调用后端全量接口（不带分页参数）
    const res = await doctorApi.getAppointmentList({
      headers: { doctorId: doctorId.value } // 请求头携带doctorId
    })

    // 适配后端返回结构（AppointmentDetailVo列表）
    appointmentOptions.value = res.data.map(item => ({
      appointmentId: item.appointmentId,
      pet: item.pet, // 关联宠物信息
      petName: item.pet?.name || '未知宠物'
    }))
  } catch (error) {
    ElMessage.error('获取预约列表失败')
  }
}

// 获取药品列表（用于下拉选项）
const fetchDrugOptions = async () => {
  try {
    const res = await doctorApi.getDrugList()
    drugOptions.value = res.data // 后端返回全量药品列表
  } catch (error) {
    ElMessage.error('获取药品列表失败')
  }
}

// 获取诊疗记录全量数据（后端返回医生专属全量数据）
const fetchAllTreatmentData = async () => {
  try {
    loading.value = true

    // 先确保获取到doctorId
    if (!doctorId.value && !(await fetchDoctorId())) {
      loading.value = false
      return
    }

    // 调用后端全量接口（请求头携带doctorId，无分页/筛选参数）
    const res = await doctorApi.getTreatmentList({
      headers: { doctorId: doctorId.value }
    })

    allTreatmentData.value = res.data || [] // 存储全量数据
    calculateStats() // 计算统计数据
    handleSearch() // 执行筛选+分页
  } catch (error) {
    ElMessage.error('获取诊疗记录失败')
  } finally {
    loading.value = false
  }
}

// 前端筛选逻辑（关键词+预约ID+日期范围）
const handleSearch = () => {
  let filteredData = [...allTreatmentData.value]

  // 1. 关键词筛选（宠物名称/诊断结果）
  if (searchForm.keyword.trim()) {
    const keyword = searchForm.keyword.trim().toLowerCase()
    filteredData = filteredData.filter(item => {
      const petName = item.appointment.pet?.name?.toLowerCase() || ''
      const diagnosis = item.diagnosis?.toLowerCase() || ''
      return petName.includes(keyword) || diagnosis.includes(keyword)
    })
  }

  // 2. 预约ID筛选
  if (searchForm.appointmentId) {
    filteredData = filteredData.filter(item =>
      item.appointment.appointmentId === searchForm.appointmentId
    )
  }

  // 3. 日期范围筛选
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const startDate = new Date(searchForm.dateRange[0])
    const endDate = new Date(searchForm.dateRange[1])
    // 结束日期加1天，包含结束日期当天
    endDate.setDate(endDate.getDate() + 1)

    filteredData = filteredData.filter(item => {
      const createDate = new Date(item.createDate)
      return createDate >= startDate && createDate < endDate
    })
  }

  // 筛选后的总条数
  filteredTotal.value = filteredData.length
  // 执行分页
  handlePagination(filteredData)
}

// 前端分页逻辑
const handlePagination = (data) => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  treatmentList.value = data.slice(startIndex, endIndex)
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  handleSearch() // 重新筛选+分页
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  handleSearch() // 重新筛选+分页
}

// 刷新列表（重新获取全量数据）
const handleRefresh = () => {
  // 重置搜索条件
  searchForm.keyword = ''
  searchForm.appointmentId = ''
  searchForm.dateRange = []
  // 重置页码
  currentPage.value = 1
  // 重新获取全量数据
  fetchAllTreatmentData()
}

// 计算统计数据（今日/本月/累计诊疗数、累计收入）
const calculateStats = () => {
  const today = new Date()
  const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)

  let todayCount = 0
  let monthCount = 0
  let totalCount = allTreatmentData.value.length
  let totalMoney = 0

  allTreatmentData.value.forEach(item => {
    const createDate = new Date(item.createDate)
    const cost = item.cost || 0

    // 累计收入
    totalMoney += cost

    // 今日诊疗数
    if (createDate >= todayStart) {
      todayCount++
    }

    // 本月诊疗数
    if (createDate >= monthStart) {
      monthCount++
    }
  })

  todayTreatmentCount.value = todayCount
  monthTreatmentCount.value = monthCount
  totalTreatmentCount.value = totalCount
  totalIncome.value = totalMoney
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    // 直接使用本地全量数据（无需重新请求接口）
    const detail = allTreatmentData.value.find(item => item.treatmentId === row.treatmentId)
    if (detail) {
      currentTreatment.value = { ...detail }
      detailVisible.value = true
    } else {
      // 本地未找到， fallback 到接口请求
      const res = await doctorApi.getTreatmentInfo(row.treatmentId, {
        headers: { doctorId: doctorId.value }
      })
      currentTreatment.value = res.data
      detailVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取诊疗详情失败')
  }
}

// 关闭详情弹窗
const handleDetailClose = () => {
  currentTreatment.value = {
    appointment: {
      pet: {},
      petOwner: {},
      ownerUser: {}
    },
    drugs: []
  }
}

// 新增诊疗记录
const handleAddTreatment = async () => {
  // 先确保获取到doctorId
  if (!doctorId.value && !(await fetchDoctorId())) {
    return
  }

  isEdit.value = false
  // 重置表单
  treatmentForm.treatmentId = ''
  treatmentForm.appointmentId = ''
  treatmentForm.diagnosis = ''
  treatmentForm.treatmentPlan = ''
  treatmentForm.drugIds = []
  treatmentForm.cost = 0

  formVisible.value = true
  // 确保下拉选项已加载
  if (appointmentOptions.value.length === 0) {
    fetchAppointmentOptions()
  }
  if (drugOptions.value.length === 0) {
    fetchDrugOptions()
  }
}

// 编辑诊疗记录
const handleEditTreatment = async (row) => {
  // 先确保获取到doctorId
  if (!doctorId.value && !(await fetchDoctorId())) {
    return
  }

  isEdit.value = true
  // 赋值表单（适配后端返回结构）
  treatmentForm.treatmentId = row.treatmentId
  treatmentForm.appointmentId = row.appointment?.appointmentId
  treatmentForm.diagnosis = row.diagnosis
  treatmentForm.treatmentPlan = row.treatmentPlan
  treatmentForm.drugIds = row.drugs?.map(drug => drug.drugId) || []
  treatmentForm.cost = row.cost

  formVisible.value = true
  // 确保下拉选项已加载
  if (appointmentOptions.value.length === 0) {
    fetchAppointmentOptions()
  }
  if (drugOptions.value.length === 0) {
    fetchDrugOptions()
  }
}

// 提交表单（新增/编辑）
const handleFormSubmit = async () => {
  try {
    await treatmentFormRef.value.validate()

    // 构造提交数据（drugIds转为JSON字符串，请求头携带doctorId）
    const submitData = {
      ...treatmentForm,
      drugIds: JSON.stringify(treatmentForm.drugIds)
    }

    if (isEdit.value) {
      await doctorApi.editTreatment(submitData, {
        headers: { doctorId: doctorId.value }
      })
      ElMessage.success('编辑诊疗记录成功')
    } else {
      await doctorApi.addTreatment(submitData, {
        headers: { doctorId: doctorId.value }
      })
      ElMessage.success('新增诊疗记录成功')
    }

    formVisible.value = false
    fetchAllTreatmentData() // 重新获取全量数据
  } catch (error) {
    ElMessage.error(isEdit.value ? '编辑诊疗记录失败' : '新增诊疗记录失败')
  }
}

// 删除诊疗记录
const handleDeleteTreatment = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该诊疗记录吗？删除后不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await doctorApi.deleteTreatment(row.treatmentId, {
      headers: { doctorId: doctorId.value }
    })
    ElMessage.success('删除成功')
    fetchAllTreatmentData() // 重新获取全量数据
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 页面挂载时初始化（先获取doctorId，再加载数据）
onMounted(async () => {
  // 第一步：获取doctorId
  await fetchDoctorId()
  // 第二步：加载全量数据和下拉选项
  fetchAllTreatmentData()
  fetchAppointmentOptions()
  fetchDrugOptions()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;

  .search-input {
    width: 100%;
  }

  .status-select {
    width: 100%;
  }

  .date-picker {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}

.consult-stats {
  .stat-card {
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 15px;

    .stat-header {
      display: flex;
      align-items: center;
      gap: 10px;

      .stat-icon {
        font-size: 20px;
        color: #409eff;
      }

      h4 {
        font-size: 14px;
        color: #666;
        font-weight: normal;
      }
    }

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }
}

.treatment-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e6e6e6;

    .header-left {
      display: flex;
      align-items: center;
      gap: 10px;

      h3 {
        font-size: 16px;
        font-weight: 600;
      }
    }

    .header-right {
      text-align: right;

      p {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }
    }
  }

  .detail-section {
    margin-bottom: 20px;

    h4 {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 10px;
      color: #333;
      padding-left: 5px;
      border-left: 3px solid #409eff;
    }
  }

  .no-data {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
  }

  .drug-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    justify-content: center;
  }
}

.form-hint {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.el-table {
  margin-bottom: 15px;
}

.el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
}
</style>